package Case;

import java.io.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 周斌
 * Date: 2024-07-01
 * Time: 9:19
 */
public class Deom3 {
    public static void main(String[] args) throws IOException {
        //1,输入必要的信息
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入你要搜索的路径：");
        String rootPath = scanner.nextLine();
        System.out.println("请输入你要查询的词：");
        String searchWord = scanner.nextLine();
        //2.检验路径的合法性
        File rootFile = new File(rootPath);
        if(!rootFile.isDirectory()) {
            System.out.println("输入的路径不合法");
            return;
        }
        //递归查询
        searchFile(rootFile,searchWord);
    }

    private static void searchFile(File rootFile, String searchWord) throws IOException {
        //列出当前目录中的所有文件和目录
        File[] files = rootFile.listFiles();
        //判断文件是否为空，并将这个条件可以作为递归结束的条件
        if(files == null) {
            return;
        }
        for (File f :files) {
            //判断f是否为一个普通文件
            if(f.isFile()) {
                //将文件中的内容读出来，与查询词比较，文件中有包含查询词则返回该文件的绝对路径
               matchWord(f,searchWord);
            } else if (f.isDirectory()) {
                //递归子目录
                searchFile(f,searchWord);
            }
        }
    }

    private static void matchWord(File f, String searchWord) throws IOException{
        try(Reader reader = new FileReader(f)) {
            StringBuilder stringBuilder = new StringBuilder();
            while(true) {
                int b = reader.read();
                if(b == -1) {
                    break;
                    //将每读的一个字符拼接到stringBuilder中
                }
                stringBuilder.append((char)b);
            }
            //再判断stringBuilder是否含有searchWord
            if (stringBuilder.indexOf(searchWord) >= 0) {
                System.out.println("找到了，位置在：" + f.getAbsolutePath());
            }
        }
    }
}

